package org.xhnews.parsers;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Vector;

import org.xhnews.log.RaspberryLogger;
import org.xhnews.to.Contact;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class ContactPullXMLParser {
	public static Vector readContacts(InputStream inputStream,
			String inputEncoding) {
		try {
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			XmlPullParser pullParser = pullParserFactory.newPullParser();
			Reader reader = new InputStreamReader(inputStream, inputEncoding);
			reader.read();
			pullParser.setInput(reader);
			int eventType = pullParser.getEventType();
			Vector contacts=new Vector();
			Contact c = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = pullParser.getName();
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					if ("user".equals(nodeName)) {
						c = new Contact();
						String id = pullParser.getAttributeValue(null, "id");
						String name = pullParser
								.getAttributeValue(null, "name");
						String type = pullParser
								.getAttributeValue(null, "type");
						String groupid = pullParser.getAttributeValue(null,
								"groupid");
						c.setId(id);
						c.setName(name);
						c.setType(type);
						c.setGroupId(groupid);
						contacts.addElement(c);
					}
					break;
				case XmlPullParser.END_TAG:
					c = null;
					break;
				}
				eventType = pullParser.next();
			}// end while
			return contacts;
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

}
